<template>
  <van-cell-group v-if="viewLoading" style="padding-bottom: 50px;">
    <van-cell title="收款账号" :value="resData.sell_user.account" />
    <van-cell title="收款手机号" :value="resData.sell_user.cellphone" />
    <van-cell title="收款云付通" :value="resData.sell_user.cloud_account" />
    <van-cell title="收款名称" :value="resData.sell_user.name" />
    <van-cell title="打款数量" :value="resData.user_mutually_buy_average.amount" />
    <van-cell title="匹配时间" :value="dayjs(resData.user_mutually_buy_average.match_time*1000).format('MM-DD HH:mm:ss')" />
    <van-field readonly
      label="打款倒计时" v-model="matchTimeCountDown"
    >
      <van-button v-if="resData.user_mutually_buy_average.reset_match < this.configApi.parameters.USER_MUTUALLY_BUY_RESET_MATCH_TIME_NUMBER.value"
        slot="button" size="small" type="primary" :loading="onResetMatchButtonLoading" @click="onResetMatch">延时</van-button>
    </van-field>

    <van-field class="van-cell--center" type="password" placeholder="请输入安全密码" name="safe_password" required
      label="安全密码" v-model="formFields.safe_password"
      :error="errors.has('safe_password')" :error-message="errors.first('safe_password')"
      data-vv-as="安全密码" v-validate="{required: true, min: 6}"
    />

    <van-cell title="凭证图片">
      <van-uploader accept="image/gif, image/jpeg, image/png" :max-size="1048576" @oversize="uploaderOversize" :after-read="uploaderAfterRead" class="van-field__control">点击上传</van-uploader>
    </van-cell>
    <van-cell v-if="uploaderShowContent" title="凭证图片">
      <img style="height: 100px;" :src="uploaderShowContent">
    </van-cell>
    <van-button size="small" type="primary" :loading="onButtonLoading" @click="onSubmit" style="width: 100%;">确认打款</van-button>
  </van-cell-group>
</template>

<script>
  import dayjs from 'dayjs';
  import { mapState } from 'vuex';
  import { Button, Cell, CellGroup, Field, Toast, Uploader } from 'vant';
  import userMutuallyBuyApi from '@/api/user/mutually/buy/index';

  export default {
    components: {
      [Button.name]: Button,
      [Cell.name]: Cell,
      [CellGroup.name]: CellGroup,
      [Field.name]: Field,
      [Uploader.name]: Uploader
    },
    data() {
      return {
        matchTimeCountDown: '',
        uploaderShowContent: '',
        resData: {},
        formFields: {
          safe_password: '',
          imageContent: ''
        },
        onResetMatchButtonLoading: false,
        onButtonLoading: false,
        viewLoading: false,
        timer: ''
      };
    },
    methods: {
      uploaderOversize(file) {
        Toast('图片过大,请压缩后上传!');
      },
      uploaderAfterRead(file) {
        this.uploaderShowContent = file.content;
        this.formFields.imageContent = file.content;
      },
      countDown(EndTime) {
        var NowTime = new Date();
        var t = EndTime - NowTime.getTime();
        var _this = this;
        if(EndTime != '0' && t > 0) {
          clearInterval(this.timer);
          this.timer = setInterval(function() {
            var NowTime = new Date();
            var t = EndTime - NowTime.getTime();
            var h = 0;
            var m = 0;
            var s = 0;
            if(t >= 0) {
              h = Math.floor(t / 1000 / 60 / 60 % 24);
              m = Math.floor(t / 1000 / 60 % 60);
              s = Math.floor(t / 1000 % 60);
            }
            _this.matchTimeCountDown = h + '时' + m + '分' + s + '秒';
          }, 1000);
        } else {
          _this.matchTimeCountDown = '已超时';
        }
      },
      onResetMatch() {
        this.onResetMatchButtonLoading = true;
        userMutuallyBuyApi.updateResetMatchTimeByToken(this.resData.user_mutually_buy_average.id).then((res) => {
          Toast(res.msg);
          this.onResetMatchButtonLoading = false;
          if(parseInt(res.code) !== 0) {
            return false;
          }
          this.getData();
          this.$store.commit('user/setUserWallet', res.user_wallet);
        }).catch(() => {
          this.onResetMatchButtonLoading = false;
        });
      },
      onSubmit() {
        this.onButtonLoading = true;
        this.$validator.validateAll().then((isValid) => {
          if(isValid) {
            userMutuallyBuyApi.updateStatusByToken(this.resData.user_mutually_buy_average.id, 31, this.formFields).then((res) => {
              Toast(res.msg);
              if(parseInt(res.code) !== 0) {
                this.onButtonLoading = false;
                return false;
              }
              setTimeout(() => {
                Toast.clear();
                this.$router.push({ name: 'mutuallyBuyRecord' });
              }, 1000);
            }).catch(()=>{
              this.onButtonLoading = false;
            });
          } else {
            Toast('请输入必要栏目');
            this.onButtonLoading = false;
          }
        }).catch(() => {
          this.onButtonLoading = false;
        });
      },
      getData() {
        userMutuallyBuyApi.findFristByIdAndToken(this.$route.query.id).then((res) => {
          this.resData = res;
          this.countDown(
            (res.user_mutually_buy_average.match_time*1000 +
            this.configApi.parameters.USER_MUTUALLY_BUY_MATCH_TIME_COUNT_DOWN_AMOUNT.value * 3600000)
          );
          this.viewLoading = true;
        });
      },
      dayjs: dayjs
    },
    computed: mapState({
      configApi: state => state.configApi,
    }),
    created() {
      this.$store.dispatch('configApi/get').then((res) => {
        this.getData();
      });
    }
  }
</script>
